package cn.ljlao.mallsearch.service.impl;

import cn.ljlao.common.dto.es.SkuEsModel;
import cn.ljlao.mallsearch.config.GulimallElasticSearchConfig;
import cn.ljlao.mallsearch.constant.EsConstant;
import cn.ljlao.mallsearch.service.ProductSaveService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Author: LiuZhen
 * @Created: 2021/8/1 22:22
 * @Description:
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;


    /**
     * 商品上架保存es
     * @param skuEsModels
     */
    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到es
        //1. 给es 中建立索引, product 建立好映射关系
        // 2. 给es 中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //1.构建保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 设置id
            indexRequest.id(skuEsModel.getSkuId().toString());
            // 请求参数 json
            String jsonString = JSON.toJSONString(skuEsModel);
            // 封装
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        boolean b = bulk.hasFailures();
        log.info("批量上传结果:{}",b);
        return b;
    }
}
